<template>
  <div class="workflow-view">
    <div class="header">
      <h2>工作流管理</h2>
      <el-button-group>
        <el-button type="primary" @click="createWorkflow">
          创建工作流
        </el-button>
      </el-button-group>
    </div>

    <!-- 工作流列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search">
            <el-input
              v-model="searchQuery"
              placeholder="搜索工作流"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filters">
            <el-select v-model="filters.type" placeholder="类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="图像处理" value="image" />
              <el-option label="文本处理" value="text" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        :data="workflows"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="名称" min-width="180">
          <template #default="{ row }">
            <div class="workflow-name">
              <el-image
                :src="row.cover"
                :preview-src-list="[row.cover]"
                fit="cover"
                class="workflow-cover"
              />
              <div class="workflow-info">
                <h3>{{ row.title }}</h3>
                <p>{{ row.description }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.type }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="editWorkflow(row)">
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteWorkflow(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { format } from 'date-fns'
import { useWorkflowStore } from '@/stores/workflow'

const router = useRouter()
const workflowStore = useWorkflowStore()

const loading = ref(false)
const searchQuery = ref('')
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const workflows = ref([])

const filters = ref({
  type: ''
})

// 获取工作流列表
const getWorkflows = async () => {
  try {
    loading.value = true
    const params = {
      page: page.value,
      limit: pageSize.value,
      search: searchQuery.value,
      type: filters.value.type
    }
    const data = await workflowStore.getWorkflows(params)
    workflows.value = data.items
    total.value = data.total
  } catch (error) {
    console.error('Failed to get workflows:', error)
    ElMessage.error('获取工作流列表失败')
  } finally {
    loading.value = false
  }
}

// 创建工作流
const createWorkflow = () => {
  router.push('/workflow/create')
}

// 编辑工作流
const editWorkflow = (workflow: any) => {
  router.push(`/workflow/${workflow.id}/edit`)
}

// 删除工作流
const deleteWorkflow = async (workflow: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该工作流吗？此操作不可恢复。',
      '删除确认',
      {
        type: 'warning'
      }
    )
    
    await workflowStore.deleteWorkflow(workflow.id)
    ElMessage.success('删除成功')
    getWorkflows()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete workflow:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理搜索
const handleSearch = () => {
  page.value = 1
  getWorkflows()
}

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getWorkflows()
}

const handlePageChange = (currentPage: number) => {
  page.value = currentPage
  getWorkflows()
}

// 格式化日期
const formatDate = (date: string) => {
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化
onMounted(() => {
  getWorkflows()
})
</script>

<style scoped lang="scss">
.workflow-view {
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search {
      width: 300px;
    }

    .filters {
      display: flex;
      gap: 16px;
    }
  }

  .workflow-name {
    display: flex;
    align-items: center;
    gap: 16px;

    .workflow-cover {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }

    .workflow-info {
      h3 {
        margin: 0 0 8px;
        font-size: 16px;
      }

      p {
        margin: 0;
        color: #666;
        font-size: 14px;
      }
    }
  }

  .pagination {
    margin-top: 24px;
    text-align: right;
  }
}
</style>